package com.smart.controller;

import com.smart.entity.Result;
import com.smart.entity.User;
import com.smart.service.IUserService;
import com.smart.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@CrossOrigin
@RequestMapping("/user")
@Api(tags = "用户相关接口")
public class UserController {
    @Autowired
    private IUserService userService;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录", response = Result.class)
    public Result login(
            @RequestBody @ApiParam(name = "用户信息", required = true) User user) {
        User login = userService.login(user);
        if (login != null) {
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id", login.getId());
            claims.put("name", login.getName());
            claims.put("role", login.getRole());
            String token = JwtUtils.generateJwt(claims);
            return Result.success(token);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户登出", response = Result.class)
    public Result logout() {
        return Result.success();
    }
}
